package model

import (
	"errors"
	"gopkg.in/gomail.v2"
	"regexp"
	"strconv"
)

//在redis中写入email:secret
func Create(email string, secret string) error {
	pattern := "[A-Z]*[0-9]*@hust.edu.cn"
	match, _ := regexp.MatchString(pattern, email)
	if match != true {
		return errors.New("非华科邮箱")
	}
	RedisDBCntlr := NewRedisDBCntlr()
	_, err := RedisDBCntlr.SETEX(email, 60*60, secret) //1h
	if err != nil {
		return err
	}
	return nil
}

//在redis验证用户的email:secret
func VerifyEmailRegister(email string, secret string) error {
	RedisDBCntlr := NewRedisDBCntlr()
	Secret, err := RedisDBCntlr.GET(email) //1h
	if err != nil {
		return err
	}
	if secret != Secret {
		return errors.New("secret error!")
	}
	return nil
}

var mailConn = map[string]string{
	"user": "1323618221@qq.com",
	"pass": "xyohdotaslsmhbdi",
	"host": "smtp.qq.com",
	"port": "587",
}

//发送邮件函数
func SendEmail(TargetEmail string, name string, C int) error {
	var subject = "Hello New count"
	port, _ := strconv.Atoi(mailConn["port"])
	m := gomail.NewMessage()
	m.SetHeader("From", m.FormatAddress(mailConn["user"], "验证码"))
	m.SetHeader("To", TargetEmail)
	m.SetHeader("Subject", subject)
	a := "<a href=" + "http://172.17.243.161:8080/set?email=" + TargetEmail + "&secret=" + strconv.Itoa(C) + "&name=" + name + ">点此确认注册</a>"
	m.SetBody("text/html", a)
	d := gomail.NewDialer(mailConn["host"], port, mailConn["user"], mailConn["pass"])
	err := d.DialAndSend(m)
	return err
}
